import Event
import grails.converters.XML
import org.springframework.dao.DataIntegrityViolationException

class EventController {

  def index = { redirect(action: list, params: params) }

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def positionList = {
    def eventInstance = Event.get(params.id)
    render(template: 'positionList', model: [eventInstance: eventInstance])
  }

  def deletePosition = {
    def eventInstance = Event.get(params.eventId)
    def positionInstance = Position.get(params.positionId)
    if (positionInstance.volunteers.size() == 0) {
      eventInstance.removeFromPositions(positionInstance)
      eventInstance.save()
      flash.put("messagePosition", "Position ${positionInstance.name} deleted")
    }
    else {
      flash.put("messagePositionError", "Volunteers must be removed from position ${positionInstance.name} before it can be deleted")
    }
    render(view: "edit", model: [eventInstance: eventInstance])
  }


  def listMyEvents = {
    def myEvents = Event.findAll("from Event as e where e.administrator=${session.user.id}")
    render(view: 'list', model: [listHeader: "Your Events", eventInstanceList: myEvents, eventInstanceTotal: myEvents.size()])

  }

  def listFutureEvents = {
    def now = new Date()
    def futureEvents = Event.findAll("from Event as e where e.startDate> now")
    def model = [listHeader: "Future Events", eventInstanceList: futureEvents, eventInstanceTotal: futureEvents.size(), feedAction: "listFutureEvents"]
    withFormat {
      xml {
        render model.eventInstanceList as XML
      }
      html {
        render(view: 'list', model: model)
      }
    }
  }

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    def model = [listHeader: "All Events", eventInstanceList: Event.list(params), eventInstanceTotal: Event.count(), feedAction: "list"]
    withFormat {
      xml {
        render model.eventInstanceList as XML
      }
      html {
        render(view: 'list', model: model)
      }
    }
  }

  def show = {
    def eventInstance = Event.get(params.id)

    if (!eventInstance) {
      flash.message = "Event not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [eventInstance: eventInstance] }
  }

  def getDetails = {
    render(view: 'getDetails', model: [eventInstance: new Event()])
  }

  def showDetails = {
    def eventInstance = Event.get(params.id)
    if (!eventInstance) {
      flash.message = "Event not found with id ${params.id}"
      redirect(action: list)
    }
    else {
      withFormat {
        xml {
          render eventInstance as XML
        }
        html {
          return [eventInstance: eventInstance]
        }
      }
    }
  }

  def delete = {
    def eventInstance = Event.get(params.id)
    if (eventInstance) {
      try {
        eventInstance.delete()
        flash.message = "Event ${params.id} deleted"
        redirect(action: list)
      }
      catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "Event ${params.id} could not be deleted"
        redirect(action: show, id: params.id)
      }
    }
    else {
      flash.message = "Event not found with id ${params.id}"
      redirect(action: list)
    }
  }

  def edit = {
    def eventInstance = Event.get(params.id)

    if (!eventInstance) {
      flash.message = "Event not found with id ${params.id}"
      redirect(action: list)
    }
    else {
      return [eventInstance: eventInstance]
    }
  }

  def update = {
    def eventInstance = Event.get(params.id)
    if (eventInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (eventInstance.version > version) {

          eventInstance.errors.rejectValue("version", "event.optimistic.locking.failure", "Another user has updated this Event while you were editing.")
          render(view: 'edit', model: [eventInstance: eventInstance])
          return
        }
      }
      eventInstance.properties = params
      if (!eventInstance.hasErrors() && eventInstance.save()) {
        flash.message = "Event ${eventInstance.name} updated"
        redirect(action: showDetails, id: eventInstance.id)
      }
      else {
        render(view: 'edit', model: [eventInstance: eventInstance])
      }
    }
    else {
      flash.message = "Event not found with id ${params.id}"
      redirect(action: edit, id: params.id)
    }
  }

  def create = {
    def eventInstance = new Event()
    eventInstance.properties = params
    eventInstance.administrator = session.user
    return ['eventInstance': eventInstance]
  }

  def save = {
    def eventInstance = new Event(params)
    eventInstance.validate()
    if (!eventInstance.hasErrors() && eventInstance.save()) {
      flash.message = "Event ${eventInstance.name} created"
      redirect(action: show, id: eventInstance.id)
    }
    else {
      render(view: 'create', model: [eventInstance: eventInstance])
    }
  }

}
